//
//  RequestManager.m
//  网络请求
//
//  Created by lanou on 16/3/11.
//  Copyright © 2016年 冯文秀. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager
+ (void)requestWithUrl:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finshed:(Finshed)finshed error:(Error)error
{
    RequestManager *manager = [[RequestManager alloc]init];
    [manager requestWithUrl:urlString requestType:requestType parDic:parDic finshed:finshed error:error];
}


- (void)requestWithUrl:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finshed:(Finshed)finshed error:(Error)error
{
    self.finshed = finshed;
    self.error = error;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    // 判断请求方式
    if (requestType == RequestTypePOST) {
        [request setHTTPMethod:@"POST"];
        // 判断字典里是否有参数
        if (parDic.count != 0) {
            [request setHTTPBody:[self dicToDataWithDic:parDic]];
        }
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            self.error(error);
        }
        else{
            self.finshed(data);
        }
    }];
    [task resume];
}

// 将字典里的键值对 按照key = value 拼接成字符串 最后用&符号连接所有拼好的字符串
- (NSData *)dicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dic) {
        NSString *string = [NSString stringWithFormat:@"%@=%@", key, dic[key]];
        [array addObject:string];
    }
    // 把数组里的东西每个用&来拼接
    NSString *dataString = [array componentsJoinedByString:@"&"];
    return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}


@end
